import {createRouter, createWebHashHistory, RouteRecordRaw} from "vue-router"
import {clearPending} from "@/api/http"
import {getMenuInfo, getToken} from "@/utils/common"
import store from "@/store"

// vite import 需要以下方式引入
const viteComponent = import.meta.glob("../views/**/*.vue")

const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        name: "base",
        redirect: "/dashboard",
        component: () => import("@/views/layout.vue"),
        // children: [
        //     {
        //         path: "/dashboard",
        //         name: "dashboard",
        //         component: () => import("@/views/dashboard.vue"),
        //     },
        //     {
        //         path: "/system/admin-user",
        //         name: "admin-user",
        //         component: () => import("@/views/system/admin-user.vue"),
        //     },
        //     {
        //         path: "/system/api",
        //         name: "api",
        //         component: () => import("@/views/system/api.vue"),
        //     },
        //     {
        //         path: "/system/menu",
        //         name: "menu",
        //         component: () => import("@/views/system/menu.vue"),
        //     },
        //     {
        //         path: "/system/role",
        //         name: "role",
        //         component: () => import("@/views/system/role.vue"),
        //     },
        //     {
        //         path: "/file-library/list",
        //         name: "file-library-list",
        //         component: () => import("@/views/file-library/list.vue"),
        //     },
        //     {
        //         path: "/file-library/group",
        //         name: "file-library-group",
        //         component: () => import("@/views/file-library/group.vue"),
        //     },
        // ],
    },
    {
        path: "/login",
        name: "login",
        component: () => import("@/views/login.vue"),
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

const appTitle = import.meta.env.VITE_APP_TITLE
// 路由守卫
router.beforeEach((to, from, next) => {
    //在跳转路由之前，先清除所有的请求
    clearPending()

    // 判断是否登录
    if (to.path === "/login") {
        next()
    } else {
        // 页面标题
        document.title = appTitle + " | " + to.meta.title

        let token = getToken()
        if (token && typeof token != "undefined") {
            // 如果vuex中没有路由数据，则获取路由数据
            if (router.getRoutes().length == routes.length) {
                getRouters().then(() => {
                    setBreadcrumb(to.path)

                    next({
                        ...to, // 无限访问目标路由, 直到 addRoute() 添加完成
                        replace: true, // 本次操作后，不能通过浏览器后退按钮，返回前一个路由
                    })
                })
            } else {
                setBreadcrumb(to.path)

                next()
            }
        } else {
            next("/login")
        }
    }
})

// 获取路由数据
const getRouters = () => {
    return new Promise((resolve) => {
        store.dispatch("initMenu", getMenuInfo()).then(() => {
            // 处理路由数据
            let data = handlerRouterDate(store.state.menus)
            // 添加路由
            data.forEach((item: any) => {
                router.addRoute("base", item)
            })

            // 在动态路由添加完成后, 才添加 404路由 否则会跳转到404页面
            router.addRoute("base", {
                path: "/:w+",
                name: "404Page",
                meta: {
                    title: "404",
                },
                component: () => import("@/views/404.vue"),
            })

            // 返回成功
            resolve(null)
        })
    })
}

// 处理路由数据
const handlerRouterDate = (data: any) => {
    let routerData = <any>[]

    // 遍历路由数据
    data.forEach((item: any) => {
        if (item.children) {
            // 递归处理子路由
            let temp = handlerRouterDate(item.children)
            // 处理完成后，添加到同一级返回
            temp.forEach((sub: any) => {
                if (sub.router != "") {
                    routerData.push(sub)
                }
            })
        }

        if (item.router != "") {
            // 处理路由数据格式
            routerData.push(handlerRouterItem(item))
        }
    })

    return routerData
}

// 处理单个路由数据
const handlerRouterItem = (item: any) => {
    return {
        path: item.router,
        name: item.key,
        // webpack 用以下方式引入
        // component: () => import(`@/views${item.path}.vue`)
        // vite 需要以下方式引入
        meta: {
            title: item.label,
        },
        component: viteComponent[`../views${item.path}.vue`],
    }
}

const setBreadcrumb = (path: string) => {
    store.commit("setBreadcrumb", getBreadcrumb(path, store.state.menus))
}

// 获取面包屑
const getBreadcrumb = (path: string, menus: any) => {
    let breadcrumbs = <any>[]

    for (let item of menus) {
        breadcrumbs = []
        breadcrumbs.push(item)

        // 如果找到了, 就跳出循环
        if (item.router == path) {
            break
        }

        if (item.children) {
            // 递归处理子路由
            let temp = getBreadcrumb(path, item.children)
            if (temp.length > 0) {
                temp.forEach((sub: any) => {
                    breadcrumbs.push(sub)
                })
            }
        }

        // 如果找到了最终结果，则跳出循环
        if (breadcrumbs[breadcrumbs.length - 1].router == path) {
            break
        }
    }

    // 如果没有找到，则返回空数组
    if (breadcrumbs.length > 0) {
        if (breadcrumbs[breadcrumbs.length - 1].router != path) {
            return []
        }
    }

    return breadcrumbs
}


export default router
